package yzx.fileutil.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import yzx.common.util.ScreenUtil;
import yzx.common.view.util.BaseRecyclerViewAdapter;
import yzx.fileutil.R;
import yzx.fileutil.util.ToastUtil;

public class SingleFileSelectFragment extends DialogFragment {


    /** 结果回调listener */
    public OnFileSelectedListener onFileSelectedListener;
    /** 一些配置 */
    public final ShowConfig config = new ShowConfig();

    private RecyclerView recyclerView;
    private TextView currentPathTv;

    private File currentPathFile = new File("/");
    private FileFilter fileFilter;
    private List<File> subFiles;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fileFilter = new FileFilter() {
            public boolean accept(File child) {
                if(config.showFile)
                    return true;
                return child.isDirectory();
            }
        };
        subFiles = Arrays.asList(currentPathFile.listFiles(fileFilter));
        Collections.sort(subFiles, new FileSorter());
        checkShowConfig();
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_file_select, container, false);
        view.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }
    /* init */
    private void init(){
        currentPathTv = (TextView) getView().findViewById(R.id.tv_current_path);
        currentPathTv.setText(currentPathFile.getAbsolutePath());
        getView().findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(currentPathFile.getParent()==null||currentPathFile.getParent().trim().isEmpty())
                    return ;
                currentPathFile = currentPathFile.getParentFile();
                subFiles = Arrays.asList(currentPathFile.listFiles(fileFilter));
                Collections.sort(subFiles, new FileSorter());
                recyclerView.scrollTo(0, 0);
                recyclerView.getAdapter().notifyDataSetChanged();
                currentPathTv.setText(currentPathFile.getAbsolutePath());
            }
        });
        recyclerView = (RecyclerView) getView().findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        /// set item Decoration
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int lr = ScreenUtil.dp2px(getActivity(), 12);
                int tb = ScreenUtil.dp2px(getActivity(), 6);
                outRect.set(lr, tb, lr, tb);
            }
        });
        /// set adapter
        recyclerView.setAdapter(new BaseRecyclerViewAdapter() {
            private View.OnClickListener onClickListener = new View.OnClickListener() {
                public void onClick(View v) {
                    File targetFile = (File) v.getTag(R.id.tagId1);
                    //item click
                    if(v.getId()==R.id.container){
                        if(targetFile.isDirectory()){
                            if(!targetFile.canRead()){
                                ToastUtil.toast(getActivity(), "无访问权限"); return ;
                            }
                            currentPathFile = targetFile;
                            subFiles = Arrays.asList(currentPathFile.listFiles(fileFilter));
                            Collections.sort(subFiles, new FileSorter());
                            recyclerView.scrollTo(0, 0);
                            notifyDataSetChanged();
                            currentPathTv.setText(currentPathFile.getAbsolutePath());
                        }else{
                            // file item click, do nothing
                        }
                    }
                    //select button click
                    else if(v.getId()==R.id.iv_selected){
                        config.dismissRun.run();
                        onFileSelectedListener.onSelected(targetFile);
                    }
                }
            };
            public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_file_select, parent, false);
                view.setOnClickListener(onClickListener);
                view.findViewById(R.id.iv_selected).setOnClickListener(onClickListener);
                return new BaseViewHolder(view);
            }
            public void onBindViewHolder(BaseViewHolder holder, int position) {
                File file = subFiles.get(position);
                /// icon
                ImageView icon = (ImageView) holder.getView(R.id.iv_icon);
                icon.setImageResource(!file.isDirectory()? config.defaultFileIcon : config.directoryIcon);
                // file name
                TextView nameTv = (TextView) holder.getView(R.id.tv_file_name);
                nameTv.setText(file.getName());
                /// for click tag
                holder.itemView.setTag(R.id.tagId1, file);
                holder.getView(R.id.iv_selected).setTag(R.id.tagId1, file);
            }
            public int getItemCount() {
                return subFiles.size();
            }
        });
    }
    /* check show config correct */
    private void checkShowConfig(){
        if(config.defaultFileIcon <1)
            throw new IllegalStateException("ShowConfig : must specify a defaultFileIcon");
        if(config.directoryIcon<1)
            throw new IllegalStateException("ShowConfig : must specify a directoryIcon");
        if(config.dismissRun==null)
            throw new IllegalStateException("ShowConfig : must specify a dismissRun");
    }

    private class FileSorter implements Comparator<File>{
        public int compare(File o1, File o2) {
            char a = o1.getName().toUpperCase().charAt(0);
            char b = o2.getName().toUpperCase().charAt(0);
            if(a>b) return 1;
            if(a<b) return -1;
            return 0;
        }
    }


    /*  =================**================= */


    public interface OnFileSelectedListener{
        void onSelected(File file);
    }
    public static class ShowConfig{
        public boolean showFile = true;
        public int directoryIcon;
        public int defaultFileIcon;
        public Runnable dismissRun;
        //public HashMap<String, Integer> fileIconMapper;
    }

}
